<template>
  <div class="app-container">
    <el-form ref="product" :model="product" :rules="rules" label-position="right" label-width="120px" status-icon>
      <el-form-item label="产品名称" prop="pname">
        <!--fetch方法会在输入时不断执行，返回相似列表-->
        <!--select则是在选择列表中的值触发-->
        <!--change则是鼠标移开时触发，select除外
        value-key是显示的值 -->
        <el-autocomplete v-model="product.pname" :fetch-suggestions="querySearchAsync"
                         :highlight-first-item="true"
                         clearable
                         placeholder="请输入产品名称"
                         value-key="pname"
                         @change="changeProduct"
                         @select="selectProduct"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="产品类别" prop="category">
        <el-select v-model="product.category" :disabled="disable" clearable placeholder="请选择产品类别">
          <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="采购数量" prop="number">
        <el-input-number v-model="buy.buyNumber" :min="1"></el-input-number>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input-number v-model="buy.buyPrice" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="buy.comment" type="textarea"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">Purchase</el-button>
        <el-button @click="onCancel">Cancel</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {getCategories} from "../../api/category";
import {getProductsByName} from "../../api/product";

export default {
  name: 'index',
  data() {
    return {
      buy: {id: 0, pid: 0, buyNumber: 0, buyPrice: 0, buyDate: null, comment: null},
      products: [],
      categories: [],
      disable: false,
      product: {
        pid: null,
        pname: null,
        category: null,
        number: 0,
      }, rules: {
        pname: [
          {required: true, message: '请输入产品名称', trigger: 'change'},
          {pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]+$/, message: "请勿输入特殊字符", trigger: "blur"},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
        ], category: [
          {required: true, message: '请选择产品类别', trigger: 'change'},
        ],
      },
    }
  },
  methods: {
    onSubmit() {
      const _this = this;
      _this.$refs.product.validate((valid) => {
        if (valid) {
          //@requestParam 和 @requestBody 联用时，@requestParam放在url，body传参
          // axios.post("/buy/buyProduct?name=" + _this.product.pname, _this.buy).then(resp => {
          //   console.log(resp.data)
          // })

          //本来是上面那个做法的，但是后面我想办法去传了两个body
          axios.post("/buy/buyProduct", {
            product: _this.product,
            buy: _this.buy
          }).then(rs => {
            if (rs.data.code === 200) {
              _this.$message.success("购买成功");
              _this.timer = setTimeout(() => {
                window.location.reload();
              }, 1000);
            } else {
              _this.$message.error(rs.data.message);
            }
          })
        }
      })
    },
    onCancel() {
      this.$message({
        message: 'cancel!',
        type: 'warning'
      })
    },
    querySearchAsync(queryString, cb) {
      const _this = this;
      getProductsByName(queryString).then(rs => {
        _this.products = rs.message;
        //返回列表
        cb(_this.products)
      })
    },
    getCategories() {
      const _this = this;
      getCategories().then(resp => {
        _this.categories = resp.message;
      })
    }, selectProduct(advice) {
      //已有产品,不能更改category
      this.setCategory(true, advice.category)
    }, changeProduct(name) {
      const _this = this;
      _this.setCategory(false, null);
      if (_this.products.length > 0) {
        //因为如果你没有select，但建议列表中有一样的值，就需要让category disable
        //从数组中找
        _this.products.forEach(item => {
          if (item.pname === name) {
            _this.setCategory(true, item.category);
          }
        })
      }
    },
    setCategory(disable, value) {
      this.disable = disable;
      this.product.category = value;
    }
  }, mounted() {
    this.getCategories();
  }
}
</script>

<style scoped>
.app-container {
  font-family: "Helvetica Neue", "Microsoft YaHei UI", sans-serif;
  font-weight: 600;
  vertical-align: middle;
  letter-spacing: 6px;
}
</style>

